package cn.zc.controller.admin;

import cn.zc.entity.*;
import cn.zc.exception.ScanException;
import cn.zc.mapper.CourceMapper;
import cn.zc.result.Result;
import cn.zc.service.StudentService;
import cn.zc.service.impl.CourceServiceImpl;
import cn.zc.utils.CourceUtils;
import cn.zc.utils.ImageUtils;
import cn.zc.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/cource")
@Slf4j
//@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.PATCH, RequestMethod.OPTIONS})
public class CourceController {
    @Autowired
    private CourceServiceImpl courceService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private CourceMapper courceMapper;
    @PostMapping("/resetkey")
    public Result resetkey(@RequestBody Map<String, String> id) {
        studentService.resetkey(id.get("id"));
        return Result.success();
    }
    @GetMapping("/getcourcebyid")
    public Result getCourceById(@RequestParam String id) {
        ErrorCourceVo errorCourceVo = new ErrorCourceVo();
        List<CourceSQL> courceSQLS = courceService.getcourcevoByid(id);
        return Result.success(courceSQLS);
    }
    @GetMapping("/loginlognum")
    public Result loginlognum() {
        int loginLognum = studentService.getLoginLogNum();
        return Result.success(loginLognum);
    }
    @GetMapping("/test")
    public String gettest() {
        return "测试成功";
    }
    /**
     * 获取登录日志
     */
    @GetMapping("/loginlog")
    public Result getLoginLog(@RequestParam int page, int pageSize) {
        List<LoginLogVo> loginLog = studentService.getLoginLog(page, pageSize);
        return Result.success(loginLog);
    }
    /**
     * 获得学生列表
     * @param
     * @return
     */
    @GetMapping("/studentList")
    public Result getStudentList(@RequestParam int currpage) {
        List<User> userList = studentService.getStudentList(currpage, 10);
        StudentListVo studentListVo = new StudentListVo();
        studentListVo.setUserList(userList);
        int studentNum = studentService.getStudentNum();
        studentListVo.setTotalCount(studentNum);
        return Result.success(studentListVo);
    }
    @PostMapping("/allimage")
    public Result getAllImage(List<MultipartFile> files) {
        List<String> errnames = new ArrayList<>();
        List<String> truenames = new ArrayList<>();
        List<String> havenames = new ArrayList<>();
        List<String> mavenames = new ArrayList<>();
        for (MultipartFile file : files) {
            String filename = file.getResource().getFilename();
            String name = filename.split("\\.")[0];
            ErrorCourceVo imageInfo = ImageUtils.getImageInfo(file);
            //TODO
            //首先将没课的添加为需要签到时间
            List<CourceSQL> courceVo = imageInfo.getCourceVo();
            String studentId = courceVo.get(0).getStudentId();
            for (int dayOfWeek = 1; dayOfWeek <= 5; dayOfWeek++) {
                // 找出对应这一天的所有元素
                int finalDayOfWeek = dayOfWeek;
                List<CourceSQL> dayCourses = courceVo.stream()
                        .filter(c -> c.getDayOfWeek() == finalDayOfWeek)
                        .collect(Collectors.toList());

                // 生成当前这一天的已有period集合
                Set<Integer> existingPeriods = dayCourses.stream()
                        .map(CourceSQL::getPeriod)
                        .collect(Collectors.toSet());

                // 周一至周五的课时是1到5，找出缺少的period
                for (int period = 1; period <= 5; period++) {
                    if (!existingPeriods.contains(period)) {
                        // 如果缺少这个period，添加新元素
                        CourceSQL courceSQL = new CourceSQL();
                        courceSQL.setPeriod(period);
                        courceSQL.setDayOfWeek(dayOfWeek);
                        courceSQL.setStart_week(0);
                        courceSQL.setEnd_week(0);
                        courceSQL.setWeekType(0);
                        courceSQL.setStudentId(studentId);
                        courceVo.add(courceSQL);
                    }
                }
            }

            //
            if(imageInfo.getErrcourceVo().isEmpty()){
                //没有问题直接添加到数据库，同时添加正确的名单
                ArrayList<CourceSQL> deleteCourceVo = new ArrayList<>();
                for (int i = 0; i < courceVo.size(); i++) {
                    CourceSQL courceSQL=courceVo.get(i);
                    if (courceSQL.getPeriod()>5||courceSQL.getPeriod()<1){
                        deleteCourceVo.add(courceSQL);
                        continue;
                    }
                    if (courceSQL.getWeekType()==0){
                        int startWeek = courceSQL.getStart_week();
                        int endWeek = courceSQL.getEnd_week();
                        courceSQL.setStart_week(startWeek);
                        courceSQL.setEnd_week(endWeek);
//                        courceSQL.setStart_week(startWeek);
//                        courceSQL.setEnd_week(endWeek);
//                        if (startWeek==endWeek&&startWeek==0){
//                            courceSQL.setStart_week(0);
//                            courceSQL.setEnd_week(0);
//                        }
//                        else if (startWeek==1&&endWeek==16){
//                            //删除cource中的
//                            deleteCourceVo.add(courceSQL);
//                        }
//                        else {
//                            List<Integer> missingNumbers = new ArrayList<>();
//                            for (int j = 1; j <= 16; j++) {
//                                if (j < startWeek || j > endWeek) {
//                                    missingNumbers.add(j);
//                                }
//                            }
//                            courceSQL.setStart_week(missingNumbers.get(0));
//                            courceSQL.setEnd_week(missingNumbers.get(missingNumbers.size() - 1));
//                        }
                    }

                    //假设startWeek为4，endWeek也为16，则将本对象的start_week设置
                }
                for (CourceSQL courceSQL:deleteCourceVo){
                    courceVo.remove(courceSQL);
                }
                //向用户表中添加数据
                User user = new User();
                user.setId(studentId);
                user.setMypassword(studentId);
                user.setName(name);
                List<CourceSQL> courceSQLS = CourceUtils.setIsOverlap(courceVo, courceMapper.getWeek());
//                courceService.insertStudentCourse(courceSQLS);
                //判断学生表中是否有该学生
                if (studentService.getStudentByStudentId(user.getId())== null) {
                    studentService.addStudent(user);
                    courceService.insertStudentCourse(courceSQLS);
                    truenames.add(name);
                    mavenames.add(filename);
                }else {
                    havenames.add(name);
                    mavenames.add(filename);
                }
            }
            //返回告诉前端都是那几张照片有问题
            if(!imageInfo.getErrcourceVo().isEmpty()){
                errnames.add(name);
            }
        }
        for (String name : mavenames) {
            // 源文件路径
            String sourceFilePath = "E:\\MobileFile\\img\\"+name;
            // 目标文件路径
            String targetDirectoryPath = "E:\\MobileFile\\imghave";
            // 创建源文件和目标目录的 Path 对象
            Path sourcePath = Paths.get(sourceFilePath);
            Path targetDirectory = Paths.get(targetDirectoryPath);

            try {
                // 确保目标目录存在
                if (!Files.exists(targetDirectory)) {
                    Files.createDirectories(targetDirectory);
                }

                // 构建目标文件的 Path 对象
                Path targetPath = targetDirectory.resolve(sourcePath.getFileName());

                // 移动文件
                Files.move(sourcePath, targetPath);

                System.out.println("文件移动成功: " + targetPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        errnames.add("err01");
//        truenames.add("true01");
//        truenames.add("true02");
//        havenames.add("hav01");
//        havenames.add("hav02");
        AllImageName names = new AllImageName(errnames, truenames, havenames);
        return Result.success(names);
    }
    @PostMapping("/scanData")
    public Result scanImage(@RequestParam("image") MultipartFile image) {
        ErrorCourceVo imageInfo = ImageUtils.getImageInfo(image);
        return Result.success(imageInfo);
    }
    @PostMapping("/addData")
//    @Transactional
    public Result<Object> addData(@RequestBody List<TableData> tableDataList) {

        if(tableDataList.get(0).getStudentId() == null){
            return Result.error("学生ID不能为空");
        }
        //向用户表中添加数据
        User user = new User();
        user.setId(tableDataList.get(0).getStudentId());
        user.setMypassword(tableDataList.get(0).getStudentId());
        user.setName(tableDataList.get(0).getStudentName());
        //判断学生表中是否有该学生
        if (studentService.getStudentByStudentId(user.getId())== null) {
            studentService.addStudent(user);
        }
        //清空学生课程
        studentService.deleteStudentCourse(user.getId());
        List<CourceSQL> cources = new ArrayList<>();
        //循环打印tableDataList
        for (TableData tableData : tableDataList) {
                List<CourceSQL> text=new ArrayList<>();
                switch (tableData.getPeriod()){
                    case "1-2节":
                         text = text(1, tableData);
                        break;
                    case "3-4节":
                        text = text(2,tableData);
                        break;
                    case "5-6节":
                        text =  text(3,tableData);
                        break;
                    case "7-8节":
                        text =    text(4,tableData);
                        break;
                    case "9-10节":
                        text =   text(5,tableData);
                        break;
                    case "11-12节":
                        text =   text(6,tableData);
                        break;
                }
                cources.addAll(text);
            }
        //按照cources中的dayOfWeek从小到大排序
//        cources.sort((a, b) -> a.getDayOfWeek() - b.getDayOfWeek());
//        System.out.println(cources);
        String studentId = tableDataList.get(0).getStudentId();
        //cources集合中所有studentId都设置为studentId
        for (CourceSQL courceSQL : cources) {
            courceSQL.setStudentId(studentId);
        }
        //更改isover字段
        List<CourceSQL> courceSQLS = CourceUtils.setIsOverlap(cources, courceMapper.getWeek());
        courceService.insertStudentCourse(courceSQLS);
        return Result.success();
    }
    //前端传的没给对象都是按照节分的，num为第几节
    public static List<CourceSQL> text(int num,TableData tableData){
        List<CourceSQL> cources = new ArrayList<>();
        for (int i = 1; i < 6; i++) {
            CourceSQL courceSQL = new CourceSQL();
            courceSQL.setPeriod(num);
            courceSQL.setDayOfWeek(i);
            String str="";
            switch (i){
                case 1:
                    str = tableData.getMonday();
                    break;
                case 2:
                    str = tableData.getTuesday();
                    break;

                case 3:
                    str = tableData.getWednesday();
                    break;
                case 4:
                    str = tableData.getThursday();
                    break;
                case 5:
                    str = tableData.getFriday();
                    break;
                case 6:
                    str = tableData.getSaturday();
                    break;
            }
            int c = 0;
            if (str.startsWith("全")) {
                c = 0;
            } else if (str.startsWith("单")) {
                c = 1;
            } else if (str.startsWith("双")) {
                c = 2;
            }
            courceSQL.setWeekType(c);
            int startBracket = str.indexOf('（') >= 0? str.indexOf('（') : str.indexOf('(');
            int endBracket = str.indexOf('）') >= 0? str.indexOf('）') : str.indexOf(')');

            if (startBracket >= 0 && endBracket >= 0) {
                String rangeStr = str.substring(startBracket + 1, endBracket);
                String[] range = rangeStr.split("-");
                int[] rangeNums = Arrays.stream(range).mapToInt(Integer::parseInt).toArray();
//                if (c == 0){
//                    //逆转
//                    if (rangeNums[0] == rangeNums[1]&&rangeNums[0]==0) {
//                        rangeNums[0] = 1;
//                        rangeNums[1] = 16;
//                    }else if (rangeNums[0] == 1 && rangeNums[1] ==16 ){
//                        continue;
//                    }else {
//                        List<Integer> missingNumbers = new ArrayList<>();
//                        for (int j = 1; j <= 16; j++) {
//                            if (j < rangeNums[0] || j > rangeNums[1]) {
//                                missingNumbers.add(j);
//                            }
//                        }
//                        rangeNums[0] = missingNumbers.get(0);
//                        rangeNums[1] = missingNumbers.get(missingNumbers.size() - 1);
//                    }
//                }
                courceSQL.setStart_week(rangeNums[0]);
                courceSQL.setEnd_week(rangeNums[1]);
                }

            cources.add(courceSQL);
        }
        return cources;
    }
}